<?php
// 语音管理后台
// 本类调用cloopen.cn的类
class VoiceAction extends Action {
	#please write main account info

	private $_uid = '';
	#please write main account info
	private $main_account= 'aaf98f893fcd4a4c013fdfc3f658004b';

	#please write main token info
	private $main_token= 'c3eeb91932d14aa08ee4b6d28f223d5a';

	#please write sub account info
	private $sub_account= '000000003f744cea013fe03a763b3d5f';

	#please write sub token info
	private $sub_token= 'ff9ff616496b40bb97aa74e9e9ce792b';

	#please write voip account
	private $voip_account= '80361200000001'; 

	#please write voip password
	private $voip_password='71z194Mi';

	#please write app id
	private $app_id='ff8080813fcd4c76013fe02c74430047'; 
	/*======================================================================*\
		Function:	_initialize
		Purpose:	初始化一些参数，主要判断是否登录授权
		Input:		无	            空
		Output:		无      		空
	\*======================================================================*/
	public function _initialize(){
		
		$this->_uid = session('uid');
	//	$data = array(
	//		''	
	//	);
	//	if(!$this->_uid) $this->display("Public:login");//(503,"对不起，您登录超时了，请重新登录！",1);
		//B('Authenticate', $action);
	}
	/*======================================================================*\
		Function:	index
		Purpose:	默认显示
		Input:		无	            空
		Output:		模板输出      	#
	\*======================================================================*/
    public function index(){
		echo geneToken();
		$this->display();
    }

	public function call(){
		$this->callBack('008615226196261','008615121163326');
	}
	/*======================================================================*\
		Function:	activateVoiceService
		Purpose:	激活账号的语音服务，在cloopen上为用户注册一个子账户
		Input:		无	            空
		Output:		ajax 返回      	#
	\*======================================================================*/
	public function activateVoiceService(){
		import('@.ORG.CloopenRESTAPI');
		$Account = M('Account');
		$Cloopen = M('Cloopen');
		$param = $this->_param();
		if($param['account']){
			$user = $Account->where("account = '".$param['account']."'")->find();
			unset($user['password']);//隐藏密码
			if(!$uid = $user['uid']) $error = "找不到该用户！";
			$clo = $Cloopen->where("owner_uid = ".$user['uid'])->field('id,owner_uid,status')->find();
			if($clo['status'] == 1) $user['active'] = 1;
			else $user['active'] = 0;
			$this->assign('list',$user);
			$this->assign('input',$param['account']);
			$this->assign('error',$error);
			$this->display();
		}else if ($param['uid']) {
			logs(session('uid'),'开始激活账号'.$param['uid'],0,'',0);
			$appid = trim($param['appid']);
		    $v = $this->_activateVoiceService($param['uid'],$appid);
			
			$user = $Account->where("uid = '".$param['uid']."'")->find();
			unset($user['password']);//隐藏密码
			if(!$uid = $user['uid']) $error = "找不到该用户！";
			$clo = $Cloopen->where("owner_uid = ".$user['uid'])->field('id,owner_uid,status')->find();
			if($clo['status'] == 1) $user['active'] = 1;
			else $user['active'] = 0;
			$this->assign('list',$user);
			$this->assign('input',$param['account']);
			$this->assign('error',$error);
		    $this->display();
		}else {
		  
			$this->display();
			
		}
		
		
	}
	/*======================================================================*\
		Function:	_activateVoiceService
		Purpose:	激活账号的语音服务，在cloopen上为用户注册一个子账户
		Input:		uid	   $appid cloopen应用id         空
		Output:		return 返回      	#
	\*======================================================================*/
	public function _activateVoiceService($uid,$appid){
		import('@.ORG.CloopenRESTAPI');
		$Account = M('Account');
		$Cloopen = M('Cloopen');
		if(!$uid){
			$error = "找不到该用户！";
		}else{
			//鉴权当前提交的用户是否具有为该用户激活账号语音服务的功能
			$owner_uid = $this->_uid;
			$isSuper = $Account->where("uid = $uid AND owner_uid = 0")->find();
			//后台账号激活只能激活主账户
			if(!$isSuper) {
				logs($this->_uid,'后台账号激活只能激活主账户',0,'admin opreation'.$uid,1);
				return false;//无权限返回，有权限继续
			}
			$c = $Cloopen->where("owner_uid = '".$uid."'")->find();
			//判断账号是否激活
			if($c['status'] == 1){
				//echo "该账号已经被激活！";
				logs($uid,"该账号已经被激活！$uid",0,'admin opreation',1);
				return true;
			}else if($c['owner_uid']){
			//曾经激活过，目前是关闭状态的，重新开启即可
				$data = array('status' => 1);
				$V = $Account->where("owner_uid = '$uid'")->save($data);
				//echo "成功重新激活该账号的语音服务功能";
				if($V){
					return true;
					logs($uid,"成功重新激活该账号的语音服务功能$uid",1,'admin opreation',1);
				}else{
					logs($uid,"失败重新激活该账号的语音服务功能$uid",0,'admin opreation',0);
					return false;
				}
			}else{
			//从未激活过，激活时，新增cloopen子账号
				$account = $Account->where("uid = '$uid'")->find();
				
				if($this->_createSubAccount($uid,$account['account'],$appid)){
					//echo "新增cloopen账号并成功激活该账号的语音服务功能";
					logs($uid,"新增cloopen账号并成功激活$uid",1,'该账号的语音服务功能admin opreation',1);
					return true;
				}else{
					logs($uid,"新增cloopen账号失败导致激活失败$uid",0,'该账号的语音服务功能失败admin opreation',1);
					//echo "新增cloopen账号失败导致激活该账号的语音服务功能失败";
					return true;
					
				}
			}
			
		}
	}
	/**
	 * 创建子账户
	 * @param uid 账号的uid
	 * @param friendlyName 子账户名称 可以是邮箱(我们现在使用的是用户的账号account)
	 * @param status 子账户状态
	 * @param type 子账户类型
	 */
	protected function _createSubAccount($uid,$friendlyName,$appid = '') {
		$Cloopen = M('Cloopen');
		$Account = M('Account');
		// 创建REST对象实例
		$appid ? 1 : $appid = $this->app_id;
		$rest = new CloopenRESTAPI($this->main_account,$this->main_token,$appid);
		
		// 调用云通讯平台的创建子账号,绑定您的子账号名称
		//echo "Try to create a subaccount, binding to user $friendlyName <br/>";
	
		$account = $friendlyName;   //$Account->where("uid = $uid")->getField('account');
		
		$result = $rest->CreateSubAccount($account);
		if($result == NULL ) {
			//echo "result error!";
			return false;
		}
		// 解析XML
		$xml = simplexml_load_string(trim($result," \t\n\r"));
		if($xml->statusCode!=0) {
			$error = "error code :" . $xml->statusCode;
			//TODO 添加错误处理逻辑
			logs($uid,'创建子账户失败',1,$error);
		} else {
			//echo "create SubbAccount success<br/>";
			// 获取返回信息
			$subaccount = $xml->SubAccount;
			/*
			echo "subAccountid:".$subaccount->subAccountSid."<br/>";
			echo "subToken:".$subaccount->subToken."<br/>";
			echo "dateCreated:".$subaccount->dateCreated."<br/>";
			echo "voipAccount:".$subaccount->voipAccount."<br/>";
			echo "voipPwd:".$subaccount->voipPwd."<br/>";
			echo "status:".$subaccount->status."<br/>";
			echo "type:".$subaccount->type."<br/>"; -->
			*/
			//TODO 把云平台创建账号信息存储在您的服务器上.
			//TODO 添加成功处理逻辑 

			
			$data = array(
				'sub_account_id' => "$subaccount->subAccountSid",
				'sub_token' => "$subaccount->subToken",
				'cloopen_appid' => $appid,
				'cloopen_username'=>$account,
				'voip_account' => "$subaccount->voipAccount",
				'voip_pwd'  => "$subaccount->voipPwd",
				'status'   => 1,
				'type'	=> 1,//子账户
				'create_time' => "$subaccount->dateCreated",
				'owner_uid' => "$uid",
				'user_token' => geneToken(), //生成hash值，token
				'update_time' => datetime()
			);
			$v = $Cloopen->add($data);
			//记录日志
			if($v){
				logs($uid,'创建子账户成功',1,$account);//logs($log_uid,$log_name,$log_type,$log_description = '',$log_status = 1)
				return true;
			}else{
				logs($uid,'创建子账户失败',0,$error);
				return false;
			}
		}	 
	}
	/**
	 * Short description.
	 * @param   type    $varname    description
	 * @return  type    description
	 * @access  public or private
	 * @static  makes the class property accessible without needing an instantiation of the class
	 */
	public function setChargePWD(){
		$Parameters = M("Parameters");
		$uid = $this->_uid;
		$param = $this->_param();
		if($uid == 1){
			if($param['chargePWD']){
				$data=array(
					'value' => trim($param['chargePWD']),
					'update_time' => datetime(),
				);
				$v = $Parameters->where("name = 'charge_password'")->save($data);
				if($v){
					logs($uid,"充值密码修改成功",1,'',1);
					$this->ajaxReturn(1,"充值密码修改成功",1);
				}else{
					logs($uid,"充值密码修改失败",0,'',0);
					$this->ajaxReturn(0,"充值密码修改失败",0);
				}
			}else{
				$error = "参数不对";
			}
		}else{
			
			$this->ajaxReturn(0,"对不起，您没有权限",0);
		}
	} // end func
	/*======================================================================*\
		Function:	setVoiceConfig
		Purpose:	语音系统的设置（号码单价，通话单价）
		Input:		无	            空
		Output:		模板输出      	#
	\*======================================================================*/
	public function setVoiceConfig(){
		$Parameters = M("Parameters");
		$uid = $this->_uid;
		$param = $this->_param();
		if($uid == 1){
			if(trim($param['phone_unit_price'])){
				$data=array(
					'value' => trim($param['phone_unit_price']),
					'update_time' => datetime(),
				);
				$v = $Parameters->where("name = 'phone_unit_price'")->save($data);
				if($v){
					logs($uid,"号码单价修改成功",1,'',1);
					$this->ajaxReturn(1,"号码单价修改成功",1);
				}else{
					logs($uid,"号码单价修改失败",0,'',0);
					$this->ajaxReturn(0,"号码单价修改失败",0);
				}
			}else if (trim($param['call_unit_price'])) {
			    $data=array(
					'value' => trim($param['call_unit_price']),
					'update_time' => datetime(),
				);
				$v = $Parameters->where("name = 'call_unit_price'")->save($data);
				if($v){
					logs($uid,"通话单价修改成功",1,'',1);
					$this->ajaxReturn(1,"通话单价修改成功",1);
				}else{
					logs($uid,"通话单价修改失败",0,'',0);
					$this->ajaxReturn(0,"通话单价修改失败",0);
				}
			}else{
			    $error = "传参出错";
			}
			
			
		}else{
			
			$this->ajaxReturn(0,"对不起，您没有权限$uid",0);
		}
	
	}
	//
	/*======================================================================*\
		Function:	setCallFee 暂未用
		Purpose:	设定用户的费用或者通话时长，每分钟的费用
		Input:		无	            空
		Output:		模板输出      	#
	\*======================================================================*/
	public function setCallFee(){
		$Cloopen = M('Cloopen');
		$get= $this->_get();
		if(!$get['uid']){
			echo "找不到该用户！";
		}else if($get['calltime_available'] && $get['price']){

			$status = $Cloopen->where("owner_uid = '".$get['uid']."'")->getField('status');
			//判断账号是否激活
			if($status){
				$data = array(
					'calltime_available' => $get['calltime_available'],
					'price'	=> $get['price'],
					'update_time' => datetime()
				);
				$v = $Cloopen->where("owner_uid = '".$get['uid']."'")->save($data);
				if ($v) {
					echo '设置成功';
				} else {
					echo '设置失败';
				}
			   
			}else{
				echo "该账号还没有激活，请先激活";
				
			}
		}else{
		
			echo "可用时长和每分钟单价，不能为空！";
		}
	
	}
	/**
	 * 创建子账户
	 * @param uid 账号的uid
	 * @param friendlyName 子账户名称 可以是邮箱(我们现在使用的是用户的账号account)
	 * @param status 子账户状态
	 * @param type 子账户类型
	 */
	function createSubAccount($uid,$friendlyName) {
		$Cloopen = M('Cloopen');
		$Account = M('Account');
		// 创建REST对象实例
		$rest = new CloopenRESTAPI($this->main_account,$this->main_token,$this->app_id);
		
		// 调用云通讯平台的创建子账号,绑定您的子账号名称
		echo "Try to create a subaccount, binding to user $friendlyName <br/>";
	
		$account = $friendlyName;   //$Account->where("uid = $uid")->getField('account');
		
		$result = $rest->CreateSubAccount($account);
		if($result == NULL ) {
			echo "result error!";
			logs($uid,"新增cloopen账号失败",0,'',0);
			exit;
		}
		// 解析XML
		$xml = simplexml_load_string(trim($result," \t\n\r"));
		if($xml->statusCode!=0) {
			echo "error code :" . $xml->statusCode . "<br/>";
			//TODO 添加错误处理逻辑
			logs($uid,"新增cloopen账号失败",0,'',0);
		} else {
			echo "create SubbAccount success<br/>";
			// 获取返回信息
			$subaccount = $xml->SubAccount;
			echo "subAccountid:".$subaccount->subAccountSid."<br/>";
			echo "subToken:".$subaccount->subToken."<br/>";
			echo "dateCreated:".$subaccount->dateCreated."<br/>";
			echo "voipAccount:".$subaccount->voipAccount."<br/>";
			echo "voipPwd:".$subaccount->voipPwd."<br/>";
			echo "status:".$subaccount->status."<br/>";
			echo "type:".$subaccount->type."<br/>";
			//TODO 把云平台创建账号信息存储在您的服务器上.
			//TODO 添加成功处理逻辑 
			$data = array(
				'sub_account_id' => "$subaccount->subAccountSid",
				'sub_token' => "$subaccount->subToken",
				'voip_account' => "$subaccount->voipAccount",
				'voip_pwd'  => "$subaccount->voipPwd",
				'status'   => "$subaccount->status",
				'type'	=> "$subaccount->type",
				'create_time' => "$subaccount->dateCreated",
				'owner_uid' => "$uid",
				'user_token' => geneToken(), //生成hash值，token
				'update_time' => datetime()
			);
			logs($uid,"新增cloopen账号成功",0,"$subaccount->subAccountSid",1);
			$v = $Cloopen->add($data);
			//记入日志logs_log
		//?????????????????????????????????????????????????????????????????????
			if($v){
				logs($uid,'创建子账户成功',1);
				return true;
			}else{
				logs($uid,'创建子账户失败',0);
				return false;
			}
		}	 
	}
	/**
	 * 双向回呼
	 * @param from 主叫电话号码。号码前需加0086
	 * @param to 被叫电话号码。号码前需加0086 
	 */
	function callBack($from,$to) {
		 import('@.ORG.CloopenRESTAPI');
		 $Interviews = M('Interviews');
		 $pos_caller = strpos($from,"0086",0);
		 $pos_called = strpos($to,"0086",0);
		 //初始化拨打人账号
		 $voip_account = $this->voip_account;
		 $sub_account =  $this->sub_account;
		 $sub_token	= $this->sub_token;


		 if($pos_caller === false || $pos_caller != 0){
			  echo "请在主叫号码前正确输入0086";
		 } else if($pos_called === false || $pos_called != 0){
			  echo "请在被叫号码前正确输入0086";
		 } else {
			// 创建REST对象实例
			$rest = new CloopenRESTAPI($this->main_account,$this->main_token,$this->app_id);
			
			// 调用回拨接口
			echo "Try to make a callback,called is $to <br/>";
			$result = $rest->CallBack($from,$to,$voip_account,$sub_account,$sub_token);
			
			$data = array(
				'owner_uid'	=> $uid,
				'call_from'	=> $from,
				'call_to'	=> $to,
				'create_time' => datetime()
			);
			if($result == NULL || strpos($result,'404')) {
				//当返回404时，接口调用失败
				echo "result error!";
				$data['error_info'] = "调用REST接口失败";
				$data['call_status'] = 0;
				
			}else{
				// 解析返回结果，XML
				$xml = simplexml_load_string(trim($result," \t\n\r"));
				if($xml->statusCode!=0) {
					echo "error code :" . $xml->statusCode . "<br>";
					//TODO 添加错误处理逻辑
					$data['error_info'] = "error code :" . $xml->statusCode;
					$data['call_status'] = 0;
				} else {
					echo "callback success!<br>";
					// 获取返回信息
					$callback = $xml->CallBack;
					echo "callSid:".$callback->callSid."<br/>";
					echo "dateCreated:".$callback->dateCreated."<br/>";
				    //TODO 添加成功处理逻辑 
				    $data['call_sid'] = $callback->callSid;
					$data['conversion_starttime'] = $callback->dateCreated;
				}			
			
			}
			//记录通话
			//$data['']
			$v = $Interviews->add($data);
			//记入通话日志logs_log
		
			if($v){
				logs($uid,'通话记录写入成功','',1);
			}else{
				logs($uid,'通话记录写入失败','',0);
			}
			 
		 }         
	}
	/*======================================================================*\
		Function:	queryAccountInfo
		Purpose:	账户查询 云通讯平台收到请求后，返回主账号信息
		Input:		params	            空
		Output:		模板输出      	#
	\*======================================================================*/
	function queryAccountInfo(){

		import('@.ORG.CloopenRESTAPI');
		// 创建REST对象实例
		$rest = new CloopenRESTAPI($this->main_account,$this->main_token,$this->app_id);

		// 调用账户查询接口
		 $result = $rest->QueryAccountInfo();
		 $uid = $this->_uid;
		 if($result == NULL ) {
			 echo "result error!";
			 $data['error_info'] = "调用接口查询失败";
		 }else{
			 // 解析XML
			 $xml = simplexml_load_string(trim($result," \t\n\r"));
			 //echo $result;
			 if($xml->statusCode!=0) {
				 echo "error code :" . $xml->statusCode . "<br>";
				 //TODO 添加错误处理逻辑
				 $data['error_info'] =  "error code :" . $xml->statusCode;
				 logs($uid,"查询Cloopen账户信息失败",0,$data['error_info'],0);
			 }else{
				 //echo "query AccountInfo success!<br/>";
				 // 获取返回信息
				 $account = $xml->Account;
				 /**echo "accountSid:".$account->accountSid."<br/>";
				 echo "friendlyName:".$account->friendlyName."<br/>";
				 echo "type:".$account->type."<br/>";
				 echo "status:".$account->status."<br/>";
				 echo "dateCreated:".$account->dateCreated."<br/>";
				 echo "dateUpdated:".$account->dateUpdated."<br/>";
				 echo "balance:".$account->balance."<br/>";
				 echo "subBalance:".$account->subBalance."<br/>";
				 */
				 //TODO 添加成功处理逻辑
				 $status = "$account->status";
				 switch($status){
					case 0:
						$status = "未激活";
						break;
					case 1:
						$status = "已激活";
						break;
					case 2:
						$status = "暂停";
						break;
					case 3:
						$status = "关闭";
						break;
					default:
						$status = "未激活";
				 }
				 $data = array(
					'accountSid' => "$account->accountSid",//加双引号是为了将对象转换为字符串
					'friendly_name' => "$account->friendlyName",
					'status'   => $status,
					'type'	=> "$account->type",
					'balance'  => "$account->balance",
					'sub_balance' => "$account->subBalance",
					'create_time' => "$account->dateCreated",
					'update_time' => "$account->dateUpdated"
				);
				//获取主账户信息后，更新信息到本地数据库中
				//$v = $Cloopen->where("owner_uid = '$uid'")->save($data);
				logs($uid,"查询Cloopen账户信息成功",0,'',1);
			} 
		 }
	
		$this->assign("list",$data);
		$this->display('queryAccount');
		
	}
	/*======================================================================*\
		Function:	callRecords
		Purpose:	通话记录
		Input:		params	            空
		Output:		模板输出      	#
	\*======================================================================*/
	public function callRecords(){
		$Interviews = M('Interviews');
		$get = $this->_post();
		if(!empty($get)){
			$where = ' 1 ';
			$get['startdate']=trim($get['startdate']);
			$get['enddate']=trim($get['enddate']);
			$get['account']=trim($get['account']);
			if($get['startdate']) $where .= " AND a.create_time >= '".$get['startdate']." 00:00:00 '";
			if($get['enddate'])   $where .= " AND a.create_time  <= '".$get['enddate']." 23:59:59 '";
			if($get['account'])  $where .= " AND b.account = '".$get['account']."'";
		}else{
			$where = 1;
		}
		import('ORG.Util.Page');// 导入分页类
		$uid = $this->_uid;
	
		
		$count      = $Interviews->where($where)->count();// 查询满足要求的总记录数
		$Page       = new Page($count,10);// 实例化分页类 传入总记录数和每页显示的记录数
		$show       = $Page->show();// 分页显示输出
		// 进行分页数据查询 注意limit方法的参数要使用Page类的属性
		$Model = new Model();
		$sql = "";//join('account ON login_log.uid = account.uid')->where($where)->order('login_time')->limit($Page->firstRow.','.$Page->listRows)->
		//$user = new Model('Interviews');
		//$list =$user->join('sms_account ON sms_login_log.uid = sms_account.uid')->where($where)->order('login_time')->limit($Page->firstRow.','.$Page->listRows)->->select();
		
		$sql = "SELECT a.*,b.account,b.company_contacter
				FROM sms_interviews AS a
				LEFT JOIN sms_account AS b ON a.owner_uid = b.uid
				WHERE ".$where."
				ORDER BY a.create_time DESC
				LIMIT ".$Page->firstRow.",".$Page->listRows;
				//alert("warn",$sql);
//echo $sql;
		$list = $Model->query($sql);
		//dump($voList);
		
		
		foreach($list as $key => $value){

			if(strlen($value['call_from']) > 13) $list[$key]['call_from'] = substr($value['call_from'],4,11);
			if(strlen($value['call_to']) > 13) $list[$key]['call_to'] = substr($value['call_to'],4,11);

			if($value['conversation_starttime']) $list[$key]['conversation_starttime'] = date('Y-m-d H:i:s',strtotime($value['conversation_starttime']));
			if($value['conversation_endtime']) $list[$key]['conversation_endtime'] = date('Y-m-d H:i:s',strtotime($value['conversation_endtime']));
			$value['conversation_time']?1:$list[$key]['total_fee'] = '0.0000';
			//$list[$key]['user_remark']?1:$list[$i]['user_remark'] = "无";	
		}
		
		//dump($list);
		$this->assign('key',$get); //查询的key再次赋值到模板中。
		$this->assign('list',$list);// 赋值数据集
		$this->assign('page',$show);// 赋值分页输出
		$this->display();
	
	}
	/***************************************************************
	*   function:操作日志
	*
	***************************************************************/
	public function operationLog(){
		$log = M('Logs');
		import('ORG.Util.Page');// 导入分页类
		$count = $log->count();// 查询满足要求的总记录数
		$Page = new Page($count,10);// 实例化分页类 传入总记录数和每页显示的记录数
		$show = $Page->show();// 分页显示输出
		// 进行分页数据查询 注意limit方法的参数要使用Page类的属性
		$list = $log->field('log_uid,log_name,log_description,create_time,operate_status')->order('create_time desc')->limit($Page->firstRow.','.$Page->listRows)->select();
		$this->assign('list',$list);// 赋值数据集
		$this->assign('page',$show);// 赋值分页输出
		$this->display(); // 输出模板

	}
}